import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:myshop/app/utils/screenAdapter.dart';

import '../controllers/search_controller.dart';
import '../../../common/widget/customizeAppBar.dart';

class SearchView extends GetView<MySearchController> {
  const SearchView({super.key});

  Widget _pageBody() {
    return ListView(
      padding: EdgeInsets.fromLTRB(
        ScreenAdapter.width(20),
        ScreenAdapter.height(20),
        ScreenAdapter.width(40),
        ScreenAdapter.height(40),
      ),
      children: [
        Obx(
          () => controller.historyList.isNotEmpty
              ? _searchTags(
                  title: "搜索历史",
                  trailing: IconButton(
                    onPressed: () {
                      // 弹出对话框
                      Get.defaultDialog(
                        title: "提示",
                        middleText: "确定清空全部搜索记录吗？",
                        actions: [
                          ElevatedButton(
                            style: ButtonStyle(
                              backgroundColor: WidgetStateProperty.all(
                                Colors.blue,
                              ),
                              foregroundColor: WidgetStateProperty.all(
                                Colors.white,
                              ),
                            ),
                            onPressed: () {
                              Get.back();
                            },
                            child: Text("取消"),
                          ),
                          ElevatedButton(
                            style: ButtonStyle(
                              backgroundColor: WidgetStateProperty.all(
                                Colors.blue,
                              ),
                              foregroundColor: WidgetStateProperty.all(
                                Colors.white,
                              ),
                            ),
                            onPressed: () {
                              controller.clearHistoryData();
                              Get.back(); // 关闭对话框
                            },
                            child: Text("确定"),
                          ),
                        ],
                      );
                    },
                    icon: Icon(Icons.delete_outline),
                  ),
                )
              : SizedBox(height: 0),
        ), //搜索历史
        controller.historyList.isNotEmpty
            ? SizedBox(height: ScreenAdapter.height(70))
            : SizedBox(height: 0),
        _searchTags(
          title: "猜你想搜",
          trailing: IconButton(
            onPressed: () {
              print("refresh");
            },
            icon: Icon(Icons.refresh_outlined),
          ),
        ),
        SizedBox(height: ScreenAdapter.height(70)),
        _hotSearch(),
      ],
    );
  }

  //  底部小米热搜
  Widget _hotSearch() {
    return Column(
      children: [
        Container(
          height: ScreenAdapter.height(120),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(ScreenAdapter.radius(20)),
            image: DecorationImage(
              image: AssetImage("assets/images/hot_search.png"),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(ScreenAdapter.radius(20)),
          ),
          // width: double.infinity,
          padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(60),
            ScreenAdapter.height(60),
            ScreenAdapter.width(40),
            ScreenAdapter.height(60),
          ),
          child: GridView.builder(
            shrinkWrap:
                true, // 解决高度问题，在ListView中嵌套GridView时使用,如果外层Container没有高度，需要收缩，否则都没有高度会报错
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              mainAxisSpacing: ScreenAdapter.height(20),
              crossAxisSpacing: ScreenAdapter.width(20),
              crossAxisCount: 2,
              childAspectRatio: 3 / 1, //  宽高比
            ),
            itemCount: 10,
            itemBuilder: (BuildContext context, int index) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: ScreenAdapter.width(120),
                    child: Image.network(
                      "https://www.itying.com/images/shouji.png",
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                  SizedBox(width: ScreenAdapter.width(30)),
                  Expanded(
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "wqqjekqwjdwqhdqwjkfhwqjhqqwqwqweqewqeqw",
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                  SizedBox(width: ScreenAdapter.width(40)),
                ],
              );
            },
          ),
        ),
      ],
    );
  }

  // 搜索标题
  Widget _searchTitle({required String title, required Widget icon}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: ScreenAdapter.fontSize(36),
            fontWeight: FontWeight.bold,
          ),
        ),
        icon,
      ],
    );
  }

  Widget _searchTags({required String title, required Widget trailing}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start, // 左对齐
      children: [
        // 标题
        _searchTitle(title: title, icon: trailing),
        // SizedBox(height: ScreenAdapter.height(30)),
        Obx(
          () => Wrap(
            spacing: ScreenAdapter.width(20), // 水平间距
            runSpacing: ScreenAdapter.height(20), // 垂直间距
            children: controller.historyList.map((tag) {
              return GestureDetector(
                onLongPress: () {
                  Get.defaultDialog(
                    title: "提示",
                    middleText: "确定删除这条记录？",
                    actions: [
                      ElevatedButton(
                        style: ButtonStyle(
                          backgroundColor: WidgetStateProperty.all(Colors.blue),
                          foregroundColor: WidgetStateProperty.all(
                            Colors.white,
                          ),
                        ),
                        onPressed: () {
                          Get.back();
                        },
                        child: Text("取消"),
                      ),
                      ElevatedButton(
                        style: ButtonStyle(
                          backgroundColor: WidgetStateProperty.all(Colors.blue),
                          foregroundColor: WidgetStateProperty.all(
                            Colors.white,
                          ),
                        ),
                        onPressed: () {
                          controller.removeHistoryData(tag);
                          Get.back();
                        },
                        child: Text("确定"),
                      ),
                    ],
                  );
                },
                child: Container(
                  padding: EdgeInsets.fromLTRB(
                    ScreenAdapter.width(20),
                    ScreenAdapter.height(15),
                    ScreenAdapter.width(20),
                    ScreenAdapter.height(15),
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(
                      ScreenAdapter.width(ScreenAdapter.radius(20)),
                    ),
                    color: Colors.white,
                  ),
                  child: Text(tag),
                ),
              );
            }).toList(),
          ),
        ), // 标签可换行排列
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        showSearchFlag: "field", // 搜索文本框
        onChangedValue: (value) {
          print("搜索内容: $value");
          controller.keywords = value; // 更新搜索内容
        },
        onSubmit: (value) {
          controller.addHistoryList(value!); // 添加历史记录
          Get.offAndToNamed(
            "productlist",
            arguments: {"keywords": value},
          ); // 卸载当前页面，跳转到商品列表页面
        },
        backgroundColor: Color.fromARGB(250, 250, 250, 250),
        actions: [
          TextButton(
            onPressed: () {
              // print("搜索");
              // 替换路由 卸载当前页面，跳转到商品列表页面
              if (controller.keywords != "") {
                // 空字符和null不是同一个意思，空字符是字符串，null是空值
                controller.addHistoryList(controller.keywords!); // 添加历史记录
              }
              Get.offAndToNamed(
                "productlist",
                arguments: {"keywords": controller.keywords},
              );
            },
            child: const Text("搜索", style: TextStyle(color: Colors.black)),
          ),
        ],
      ),
      body: _pageBody(),
    );
  }
}
